package com.whmnx.my.ui.viewmodel;

import android.app.Application;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import androidx.databinding.ObservableField;

import com.alipay.sdk.app.PayTask;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.baidu.ocr.ui.camera.CameraNativeHelper;
import com.baidu.ocr.ui.camera.CameraView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.qcloud.ugckit.utils.ToastUtil;
import com.whmnx.base.bean.ImgResultBean;
import com.whmnx.base.bean.PayBean;
import com.whmnx.base.bean.PayResult;
import com.whmnx.base.bean.WeixinBean;
import com.whmnx.base.constants.Constants;
import com.whmnx.base.constants.EventConstants;
import com.whmnx.base.http.CallBack;
import com.whmnx.base.http.HttpClient;
import com.whmnx.base.utils.FileUtil;
import com.whmnx.base.utils.PhotoUtil;
import com.whmnx.base.view.CommonDialog2;
import com.whmnx.my.R;
import com.whmnx.my.databinding.FragmentRenZhengBinding;
import com.whmnx.my.ui.fragment.MyRenZhengFragment;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
import me.goldze.mvvmhabit.utils.SPUtils;

import static com.whmnx.my.ui.viewmodel.EidtModel.CODE_CAMERA_REQUEST;

/**
 * author : huang
 * date   : 2020/9/29 0029 9:28
 * version: 1.0
 */
public class RenModel extends ToolbarViewModel{
    public static final String KEY_OUTPUT_FILE_PATH = "outputFilePath";
    public static final String KEY_CONTENT_TYPE = "contentType";
    public static final String KEY_NATIVE_TOKEN = "nativeToken";
    public static final String KEY_NATIVE_ENABLE = "nativeEnable";
    public static final String KEY_NATIVE_MANUAL = "nativeEnableManual";

    public static final String CONTENT_TYPE_GENERAL = "general";
    public static final String CONTENT_TYPE_ID_CARD_FRONT = "IDCardFront";
    public static final String CONTENT_TYPE_ID_CARD_BACK = "IDCardBack";
    public static final String CONTENT_TYPE_BANK_CARD = "bankCard";
    public static final String CONTENT_TYPE_PASSPORT = "passport";

    public static final int REQUEST_CODE_CAMERA = 120;

    public static final String PHOTO_BITMAP = "photo_bitmap";

    private static final int REQUEST_CODE_PICK_IMAGE = 100;
    private static final int PERMISSIONS_REQUEST_CAMERA = 800;
    private static final int PERMISSIONS_EXTERNAL_STORAGE = 801;

    private int index = 0;

    public ObservableField<String> idCard = new ObservableField<>("");
    public ObservableField<String> userInfo_RealName = new ObservableField<>("");



    MyRenZhengFragment mFragment;
    FragmentRenZhengBinding mBinding;

    public IWXAPI mWxApi;

    private Disposable subscribe;
    private Dialog dialogHead;
    private int lv;



    private ArrayList<String> list_path = new ArrayList<>();
    private ArrayList<String> list_path2 = new ArrayList<>();


    public RenModel(@NonNull Application application) {
        super(application);
    }

    public void initToolbar(MyRenZhengFragment myRenZhengFragment, FragmentRenZhengBinding binding) {
        this.mFragment = myRenZhengFragment;
        this.mBinding = binding;
        setTitleText("V1认证");
        initView();
        initListen();
        mWxApi = WXAPIFactory.createWXAPI(mFragment, Constants.WECHAT_ID, false);
        mWxApi.registerApp(Constants.WECHAT_ID);
        lv = SPUtils.getInstance().getInt(Constants.LV);
        if (lv == 1){
           mBinding.llCode.setVisibility(View.VISIBLE);
           mBinding.tv1.setVisibility(View.GONE);
           mBinding.tv2.setVisibility(View.GONE);
           mBinding.tv3.setVisibility(View.GONE);
           mBinding.tv4.setVisibility(View.GONE);
            setTitleText("V2认证");
        }else if (lv == 2){
            mBinding.llCode.setVisibility(View.VISIBLE);
            mBinding.tv1.setVisibility(View.GONE);
            mBinding.tv2.setVisibility(View.GONE);
            mBinding.tv3.setVisibility(View.GONE);
            mBinding.tv4.setVisibility(View.GONE);
            setTitleText("V2认证");
        }
    }

    private void initAccessTokenWithAkSk() {
        OCR.getInstance(mFragment).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                Log.i("wyb", "token is " + token);
                // 本地自动识别需要初始化
                initLicense();
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                ToastUtil.toastShortMessage("AK，SK方式获取token失败");
            }
        }, getApplication(), "8YEROg4CqtfsIHdnBdU8vTHd", "kKirORxuPDs7fIkIsxetCF2oPZ7aAKTP");
    }

    private void initLicense() {
        CameraNativeHelper.init(mFragment, OCR.getInstance(mFragment).getLicense(),
                (errorCode, e) -> {
                    final String msg;
                    switch (errorCode) {
                        case CameraView.NATIVE_SOLOAD_FAIL:
                            msg = "加载so失败，请确保apk中存在ui部分的so";
                            break;
                        case CameraView.NATIVE_AUTH_FAIL:
                            msg = "授权本地质量控制token获取失败";
                            break;
                        case CameraView.NATIVE_INIT_FAIL:
                            msg = "本地质量控制";
                            break;
                        default:
                            msg = String.valueOf(errorCode);
                    }
                    mFragment.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mFragment,
                                    "本地质量控制初始化错误，错误原因： " + msg, Toast.LENGTH_SHORT).show();
                        }
                    });
                });
    }

    private void initListen() {
        mBinding.ivCode.setOnClickListener(v -> {
            Intent intent = new Intent(mFragment, CameraActivity.class);
            intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                    mFragment.getFile(mFragment.index).getAbsolutePath());
            // 推荐这样做，可以避免一些activity切换导致的不必要的异常
            intent.putExtra(CameraActivity.KEY_NATIVE_ENABLE, true);
            intent.putExtra(CameraActivity.KEY_NATIVE_MANUAL, true);
            intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
            mFragment.startActivityForResult(intent, REQUEST_CODE_CAMERA);

        });
        mBinding.ivCode2.setOnClickListener(v -> {
// 反面(自动)
            Intent intent_back = new Intent(mFragment, CameraActivity.class);
            intent_back.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                    mFragment.getFile(mFragment.index).getAbsolutePath());
            // KEY_NATIVE_MANUAL设置了之后CameraActivity中不再自动初始化和释放模型
            // 请手动使用CameraNativeHelper初始化和释放模型
            // 推荐这样做，可以避免一些activity切换导致的不必要的异常
            intent_back.putExtra(CameraActivity.KEY_NATIVE_ENABLE, true);
            intent_back.putExtra(CameraActivity.KEY_NATIVE_MANUAL, true);
            intent_back.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_BACK);
            mFragment.startActivityForResult(intent_back, REQUEST_CODE_CAMERA);
        });

        mBinding.ivCode3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mFragment.imageUri = Uri.fromFile(mFragment.fileUri);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    mFragment.imageUri = FileProvider.getUriForFile(mFragment, "com.whmnx.webcasts.FileProvider", mFragment.fileUri);
                }
                PhotoUtil.takePicture(mFragment, mFragment.imageUri, CODE_CAMERA_REQUEST);
            }
        });
    }


    private void initView() {
        subscribe = RxBus.getDefault().toObservable(Object.class)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object object){
                        if (object.equals(EventConstants.WEIXIN)){  //支付回调
                            RxBus.getDefault().post(EventConstants.IMG);
                            dialogHead.dismiss();
                            finish();
                        }
                    }
                });
        RxSubscriptions.add(subscribe);
    }




    public BindingCommand OnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (TextUtils.isEmpty(userInfo_RealName.get())){
                ToastUtil.toastShortMessage("请输入真实姓名");
                return;
            }
            if (TextUtils.isEmpty(idCard.get())){
                ToastUtil.toastShortMessage("请输入身份证号");
                return;
            }
            if (idCard.get().length() != 15 && idCard.get().length() != 18){
                ToastUtil.toastShortMessage("身份证号码长度应该为15位或18位");
                return;
            }

            if (lv == 1 || lv == 2){
                if (mFragment.flag && mFragment.flag2 ) {

                } else {
                    ToastUtil.toastShortMessage("请扫描身份证正反面");
                    return;
                }

                if (!mFragment.flag3){
                    ToastUtil.toastShortMessage("请拍手持身份证照片");
                    return;
                }

                list_path.clear();
                list_path2.clear();
                list_path.add(mFragment.filePath1);
                list_path.add(mFragment.filePath2);
                list_path.add(mFragment.cropImageUri.getPath());
                List<File> files = new ArrayList<>();
                for (String datum : list_path) {
                    File file = new File(FileUtil.compressImage(datum));
                    files.add(file);
                }

                HttpClient.postImg(mFragment, Constants.UPLOADHEADIMG, files, new CallBack<List<ImgResultBean>>() {
                    @Override
                    public void onSuccess(List<ImgResultBean> baseBean) {
                        for (ImgResultBean imgResultBean : baseBean) {
                            list_path2.add(imgResultBean.shortPath);
                        }

                        getUpdate();
                    }
                });



            }else if (lv == 0){
                String s2 = "第三方认证服务费2元";
                new CommonDialog2(mFragment, R.style.dialog, s2,"", (dialog, confirm) -> {
                    if (confirm) {
                        showPayDialog();
                    }
                    dialog.dismiss();
                }).show();
            }
        }
    });

    private void getUpdate() {
        Map<String, Object> params = new HashMap<>();
        params.put("userId",SPUtils.getInstance().getString(Constants.USERID));
        params.put("v2_Name",userInfo_RealName.get());
        params.put("v2_IdCard",idCard.get());
        if (list_path2.size() > 0) {
            params.put("v2_Img1", list_path2.get(0));
            params.put("v2_Img2", list_path2.get(1));
            params.put("v2_Img3", list_path2.get(2));
        }

        HttpClient.post(mFragment, Constants.ADDV2AUTHENTICATION, params, new CallBack<WeixinBean>() {
            @Override
            public void onSuccess(WeixinBean weixinBean) {
                RxBus.getDefault().post(EventConstants.IMG);
                finish();
            }
        });
    }

    private void showPayDialog() {
        dialogHead = new Dialog(mFragment, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(mFragment).inflate(R.layout.dialog_pay, null);

        view.findViewById(R.id.ll_wei).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                V1Authentication(0);
                dialogHead.dismiss();
            }
        });
        view.findViewById(R.id.ll_zhi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                V1Authentication(1);
                dialogHead.dismiss();
            }
        });

        dialogHead.setContentView(view);
        Window window = dialogHead.getWindow();
        if (window == null) {
            return;
        }
        //宽高最大
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        //显示对话框//设置Dialog从窗体底部弹出
        dialogHead.setCanceledOnTouchOutside(true);
        dialogHead.show();
        window.setGravity(Gravity.BOTTOM);
        //获取窗体的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置Dialog距离底部的距离
        //将属性设置给窗体
        window.setAttributes(lp);

    }

    private void V1Authentication(int type2) {
        Map<String, Object> params = new HashMap<>();
        //威信
        params.put("type",type2);
        params.put("userId", SPUtils.getInstance().getString(Constants.USERID));
        params.put("idCard",idCard.get());
        params.put("userInfo_RealName",userInfo_RealName.get());

        if (type2 == 0) {
            HttpClient.post(mFragment, Constants.V1AUTHENTICATION, params, new CallBack<WeixinBean>() {
                @Override
                public void onSuccess(WeixinBean weixinBean) {
                    PayReq req = new PayReq();
                    req.appId = weixinBean.getSign().getAppId();
                    req.partnerId = weixinBean.getSign().getPartnerId();
                    req.prepayId = weixinBean.getSign().getPrepayId();
                    req.nonceStr = weixinBean.getSign().getNonceStr();
                    req.timeStamp = weixinBean.getSign().getTimeStamp();
                    req.packageValue = weixinBean.getSign().getPackageValue();
                    req.sign = weixinBean.getSign().getSign();
                    //  req.extData = "0.02";
                    mWxApi.sendReq(req);
                }
            });
        }else {
            HttpClient.post(mFragment, Constants.V1AUTHENTICATION, params, new CallBack<PayBean>() {
                @Override
                public void onSuccess(PayBean weixinBean) {
                    Runnable payRunnable = () -> {
                        PayTask alipay = new PayTask(mFragment);
                        PayResult payResult = new PayResult((Map<String, String>) alipay.payV2(weixinBean.getSign(), true));
                        /**
                         对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                         */
                        final String resultStatus = payResult.getResultStatus();// 同步返回需要验证的信息
                        mFragment.runOnUiThread(() -> {
                            // 判断resultStatus 为9000则代表支付成功
                            if (TextUtils.equals(resultStatus, "9000")) {
                                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                                ToastUtil.toastShortMessage("支付成功");
                                dialogHead.dismiss();
                                RxBus.getDefault().post(EventConstants.IMG);
                                finish();
                                // getTradingInfo();
                            } else {
                                ToastUtil.toastShortMessage("支付失败");
                            }
                        });
                    };
                    // 必须异步调用
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                }
            });
        }
    }




    @Override
    public void onDestroy() {
        super.onDestroy();
        RxSubscriptions.remove(subscribe);
    }
}
